import { defineStore } from 'pinia'
import { ref, computed } from 'vue'

/**
 * 创作内容状态管理
 * 管理用户的图片、视频创作内容
 */
export const useCreationStore = defineStore('creation', () => {
  // 状态
  const images = ref([])
  const videos = ref([])
  const activeTab = ref('image') // 'image' 或 'video'
  const isLoading = ref(false)
  const hasLoadedOnce = ref(false)

  // 计算属性
  const currentAssets = computed(() => {
    return activeTab.value === 'image' ? images.value : videos.value
  })

  const totalImages = computed(() => images.value.length)
  const totalVideos = computed(() => videos.value.length)
  const totalCreations = computed(() => totalImages.value + totalVideos.value)

  // 方法
  /**
   * 设置加载状态
   */
  const setLoading = (loading) => {
    isLoading.value = loading
  }

  /**
   * 设置活跃标签
   */
  const setActiveTab = (tab) => {
    activeTab.value = tab
  }

  /**
   * 设置图片列表
   */
  const setImages = (imageList) => {
    images.value = imageList || []
  }

  /**
   * 设置视频列表
   */
  const setVideos = (videoList) => {
    videos.value = videoList || []
  }

  /**
   * 添加新图片
   */
  const addImage = (imageData) => {
    images.value.unshift(imageData)
  }

  /**
   * 添加新视频
   */
  const addVideo = (videoData) => {
    videos.value.unshift(videoData)
  }

  /**
   * 删除图片
   */
  const removeImage = (imageId) => {
    const index = images.value.findIndex(img => img.id === imageId)
    if (index > -1) {
      images.value.splice(index, 1)
    }
  }

  /**
   * 删除视频
   */
  const removeVideo = (videoId) => {
    const index = videos.value.findIndex(video => video.id === videoId)
    if (index > -1) {
      videos.value.splice(index, 1)
    }
  }

  /**
   * 清空所有创作内容
   */
  const clearAll = () => {
    images.value = []
    videos.value = []
    hasLoadedOnce.value = false
  }

  /**
   * 标记已加载过
   */
  const markAsLoaded = () => {
    hasLoadedOnce.value = true
  }

  /**
   * 加载用户创作历史（模拟数据）
   */
  const loadUserCreations = async (type = 'image') => {
    if (isLoading.value) return

    setLoading(true)
    try {
      // 模拟加载延迟
      await new Promise(resolve => setTimeout(resolve, 500))

      if (type === 'image') {
        // 模拟图片数据
        const mockImages = [
          {
            id: 1,
            imageUrl: '/static/c11.png',
            title: '风格化图片1',
            createTime: new Date().toLocaleDateString()
          },
          {
            id: 2,
            imageUrl: '/static/c2.png',
            title: '风格化图片2',
            createTime: new Date().toLocaleDateString()
          }
        ]
        setImages(mockImages)
      } else if (type === 'video') {
        // 模拟视频数据
        const mockVideos = [
          {
            id: 1,
            videoUrl: 'https://douyin-ai.tos-cn-shanghai.volces.com/e150904a-8d12-4098-a713-bdf45316342a.mp4',
            coverUrl: '/static/test.png',
            title: '风格化视频1',
            createTime: new Date().toLocaleDateString()
          }
        ]
        setVideos(mockVideos)
      }

      markAsLoaded()
      console.log(`加载${type}创作历史成功`)
    } catch (error) {
      console.error(`加载${type}创作历史失败:`, error)
      // 加载失败时显示空列表
      if (type === 'image') {
        setImages([])
      } else {
        setVideos([])
      }
    } finally {
      setLoading(false)
    }
  }

  /**
   * 刷新当前活跃标签的内容
   */
  const refreshCurrentTab = async () => {
    await loadUserCreations(activeTab.value)
  }

  /**
   * 切换标签并加载对应内容
   */
  const switchTab = async (tab) => {
    setActiveTab(tab)
    await loadUserCreations(tab)
  }

  /**
   * 初始化创作内容
   */
  const initializeCreations = async () => {
    if (!hasLoadedOnce.value) {
      await loadUserCreations('image') // 默认加载图片
    }
  }

  return {
    // 状态
    images,
    videos,
    activeTab,
    isLoading,
    hasLoadedOnce,
    
    // 计算属性
    currentAssets,
    totalImages,
    totalVideos,
    totalCreations,
    
    // 方法
    setLoading,
    setActiveTab,
    setImages,
    setVideos,
    addImage,
    addVideo,
    removeImage,
    removeVideo,
    clearAll,
    markAsLoaded,
    loadUserCreations,
    refreshCurrentTab,
    switchTab,
    initializeCreations
  }
})
